/**
 * 页面加载优化工具
 * 用于减少页面闪烁和提升用户体验
 */

// 页面预加载缓存
const pageCache = new Map<string, any>();

/**
 * 设置页面缓存
 * @param key 缓存键
 * @param data 缓存数据
 * @param ttl 过期时间（毫秒），默认5分钟
 */
export const setPageCache = (key: string, data: any, ttl: number = 5 * 60 * 1000) => {
  const expireTime = Date.now() + ttl;
  pageCache.set(key, {
    data,
    expireTime
  });
};

/**
 * 获取页面缓存
 * @param key 缓存键
 * @returns 缓存数据或null
 */
export const getPageCache = (key: string) => {
  const cached = pageCache.get(key);
  if (!cached) return null;
  
  // 检查是否过期
  if (Date.now() > cached.expireTime) {
    pageCache.delete(key);
    return null;
  }
  
  return cached.data;
};

/**
 * 清除页面缓存
 * @param key 缓存键，不传则清除所有
 */
export const clearPageCache = (key?: string) => {
  if (key) {
    pageCache.delete(key);
  } else {
    pageCache.clear();
  }
};

/**
 * 防抖函数
 * @param func 要防抖的函数
 * @param delay 延迟时间
 * @returns 防抖后的函数
 */
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
};

/**
 * 节流函数
 * @param func 要节流的函数
 * @param delay 延迟时间
 * @returns 节流后的函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let lastCall = 0;
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
};

/**
 * 延迟执行函数，避免阻塞渲染
 * @param func 要执行的函数
 * @param delay 延迟时间，默认使用requestAnimationFrame
 */
export const deferExecution = (func: () => void, delay?: number) => {
  if (delay !== undefined) {
    setTimeout(func, delay);
  } else {
    requestAnimationFrame(func);
  }
};

/**
 * 页面可见性检测
 * @param callback 页面可见时的回调
 * @param hiddenCallback 页面隐藏时的回调
 */
export const onPageVisibilityChange = (
  callback: () => void,
  hiddenCallback?: () => void
) => {
  const handleVisibilityChange = () => {
    if (document.hidden) {
      hiddenCallback?.();
    } else {
      callback();
    }
  };
  
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 返回清理函数
  return () => {
    document.removeEventListener('visibilitychange', handleVisibilityChange);
  };
};

/**
 * 图片预加载
 * @param urls 图片URL数组
 * @returns Promise
 */
export const preloadImages = (urls: string[]): Promise<void[]> => {
  const promises = urls.map(url => {
    return new Promise<void>((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => reject(new Error(`Failed to load image: ${url}`));
      img.src = url;
    });
  });
  
  return Promise.all(promises);
};